package com.lottery.ruok.lottrey.chat.view;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.activity.ChooseLotteryActivity;
import com.lottery.ruok.lottrey.common.Common;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.GetWholeCategoryRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.GetWholeCategoryResponse;
import com.lottery.ruok.lottrey.ui.component.BaseRelativeLayout;
import com.lottery.ruok.lottrey.userInfo.UserInfo;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import count_down.CountDownManager;
import ui.AreaCircle;
import utils.StringUtils;
import utils.Utils;

/**
 * 聊天室开奖view
 */
public class ChatRoomLotteryView extends BaseRelativeLayout {

    @BindView(R.id.tv_lottery_name)
    TextView tvLotteryName;
    @BindView(R.id.tv_lottery_time)
    TextView tvLotteryTime;
    @BindView(R.id.tv_lottery_result)
    TextView tvLotteryResult;
    @BindView(R.id.view_content_container)
    LinearLayout viewContentContainer;
    @BindView(R.id.view_chatroom_lottery_container)
    RelativeLayout viewChatroomLotteryContainer;
    @BindView(R.id.iv_switch)
    ImageView ivSwitch;
    @BindView(R.id.view_balls_container)
    LinearLayout viewBallsContainer;
    private String lotteryCode;
    private GetWholeCategoryResponse.ItemsBean data;
    private GetWholeCategoryResponse.AttachedBean attached;
    private CountDownManager.CountDownModel countDownModel;
    private ValueAnimator valueAnimator;

    public ChatRoomLotteryView(Context context) {
        super(context);
    }

    public ChatRoomLotteryView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ChatRoomLotteryView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void init(Context context, AttributeSet attrs, int defStyleAttr) {

    }


    @Override
    protected void initView(Context context) {
        setContentView(R.layout.view_chat_room_lottery);
        ivSwitch.setSelected(true);
        initAnimator();
    }

    @Override
    protected void load(Context context) {

    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        countDownModel = new CountDownManager.CountDownModel() {
            public boolean isLoading;

            @Override
            public void onExecute() {
                if (data != null) {
                    data.setTime(data.getTime() - 1);
                    if (data.getTime() >= 0) {
                        isLoading = false;
                        tvLotteryTime.setText(utils.Utils.getCountTimeByLong(data.getTime() * 1000));
                    } else {
                        if (!isLoading) {
                            isLoading = true;
                            loadLotteryDetail();
                        }
                    }

                }
            }
        };
        CountDownManager.asInstance().register(countDownModel);
    }

    @Override
    protected void onDetachedFromWindow() {
        CountDownManager.asInstance().unRegister(countDownModel);
        super.onDetachedFromWindow();
    }

    /**
     * 设置菜种
     *
     * @param lotteryCode
     */
    public void setLotteryCode(String lotteryCode) {
        this.lotteryCode = lotteryCode;
        loadLotteryDetail();
    }

    /**
     * 设置开奖结果
     *
     * @param lotteryResult
     */
    public void setLotteryReuslt(String lotteryResult) {
        if (data != null) {
            data.setPrize_num(lotteryResult);
        }
        updateBallsView();
    }

    /**
     * 加载彩票详情
     */
    public void loadLotteryDetail() {
        if (StringUtils.isEmpty(lotteryCode)) {
            return;
        }
        RetrofitBase.getRetrofit().create(GetWholeCategoryRequest.class).getResult(UserInfo.getToken(), 0, 0)
                .compose(RxHelper.<ArrayList<GetWholeCategoryResponse>>handleResult())
                .subscribe(new RxSubscribe<ArrayList<GetWholeCategoryResponse>>(mContext) {
                    @Override
                    protected void _onNext(ArrayList<GetWholeCategoryResponse> data) {
                        getDataByLotteryCode(data, lotteryCode);
                    }

                    private void getDataByLotteryCode(ArrayList<GetWholeCategoryResponse> data, String lotteryCode) {
                        if (data != null) {
                            Iterator<GetWholeCategoryResponse> iterator = data.iterator();
                            while (iterator.hasNext()) {
                                GetWholeCategoryResponse next = iterator.next();
                                if (next != null) {
                                    List<GetWholeCategoryResponse.ItemsBean> items = next.getItems();
                                    if (items != null) {
                                        Iterator<GetWholeCategoryResponse.ItemsBean> itemIterator = items.iterator();
                                        while (itemIterator.hasNext()) {
                                            GetWholeCategoryResponse.ItemsBean item = itemIterator.next();

                                            if (item != null && item.getCode().equals(lotteryCode)) {
                                                if ("xglhc".equals(item.getCode()) || "jslhc".equals(item.getCode())|| "js10flhc".equals(item.getCode())) {//香港六合彩开奖特殊情况
                                                    attached = item.getAttached();
                                                }
                                                //找到对应的数据
                                                setData(item);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }


                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });

    }


    public void setData(GetWholeCategoryResponse.ItemsBean data) {
        this.data = data;
        updateView();
    }

    private void updateView() {
        if (data != null) {
            tvLotteryName.setText(data.getName());
            updateBallsView();
        }
    }

    public void updateBallsView() {
        if (lotteryCode.equals("xglhc") || lotteryCode.equals("jslhc")|| lotteryCode.equals("js10flhc")) {//香港六合彩开奖特殊情况
            String[] p = data.getPrize_num().split(",");
            if (p != null && p.length > 1 && !p[0].equals("")) {
                viewBallsContainer.removeAllViews();
                viewBallsContainer.setVisibility(VISIBLE);
                tvLotteryResult.setVisibility(View.INVISIBLE);
                for (int i = 0; i < p.length; i++) {
                    TextView areaCircle = new TextView(mContext);
                    if (attached != null) {
                        switch (attached.getColor().get(i)) {
                            case "green":
                                areaCircle.setBackgroundResource(R.mipmap.green_big);
                                break;
                            case "red":
                                areaCircle.setBackgroundResource(R.mipmap.red_big);
                                break;
                            case "blue":
                                areaCircle.setBackgroundResource(R.mipmap.blue_big);
                                break;
                        }
                    }
                    areaCircle.setTextColor(getResources().getColor(R.color.lottery_black));
                    areaCircle.setGravity(Gravity.CENTER);
                    areaCircle.setText(p[i]);
                    areaCircle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11);
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(utils.Utils.dip2px(mContext, 20), utils.Utils.dip2px(mContext, 20));
                    layoutParams.rightMargin = utils.Utils.dip2px(mContext, 6);
                    layoutParams.gravity = Gravity.CENTER;
                    areaCircle.setLayoutParams(layoutParams);
                    viewBallsContainer.addView(areaCircle);
                }
            } else {
                viewBallsContainer.setVisibility(View.GONE);
                tvLotteryResult.setVisibility(VISIBLE);
            }
        } else {
            String[] p = data.getPrize_num().split(",");
            if (p != null && p.length > 1 && !p[0].equals("")) {
                viewBallsContainer.setVisibility(VISIBLE);
                tvLotteryResult.setVisibility(View.GONE);
                viewBallsContainer.removeAllViews();
                for (String s : p) {
                    AreaCircle areaCircle = new AreaCircle(mContext.getApplicationContext());
                    Common.setBallBackground(areaCircle, s, lotteryCode);

                    areaCircle.setText(s);
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(utils.Utils.dip2px(mContext, 20), utils.Utils.dip2px(mContext, 20));
                    layoutParams.rightMargin = utils.Utils.dip2px(mContext, 6);
                    areaCircle.setLayoutParams(layoutParams);
                    viewBallsContainer.addView(areaCircle);
                }
            } else {
                viewBallsContainer.setVisibility(View.GONE);
                tvLotteryResult.setVisibility(VISIBLE);
            }
        }
    }

    @OnClick({R.id.iv_switch, R.id.tv_lottery_name})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_switch:
                ivSwitch.setSelected(!ivSwitch.isSelected());
                if (valueAnimator != null) {
                    valueAnimator.start();
                }
                break;

            case R.id.tv_lottery_name://
                ChooseLotteryActivity.startActivity((Activity) mContext, lotteryCode);
                break;

        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == ChooseLotteryActivity.REPONSE_CODE) {
            if (data != null) {
                String lotteryCode = data.getStringExtra("code");

                if (!StringUtils.isEmpty(lotteryCode)) {
                    setLotteryCode(lotteryCode);
                }
            }
        }
    }

    public String getLotteryCode() {
        return lotteryCode;
    }

    private void initAnimator() {
        valueAnimator = ValueAnimator.ofFloat(0, 1);
        valueAnimator.setDuration(500);
        valueAnimator.setRepeatCount(0);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                float value = (float) valueAnimator.getAnimatedValue();
                boolean isShow = ivSwitch.isSelected();
                float tempValue = 0;
                if (isShow) {
                    tempValue = 1 - value;
                } else {
                    tempValue = value;
                }
                int width = viewChatroomLotteryContainer.getWidth() - Utils.dip2px(mContext, 30);
                viewChatroomLotteryContainer.setTranslationX(tempValue * width);
            }
        });
        valueAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {
                ivSwitch.setEnabled(false);
            }

            @Override
            public void onAnimationEnd(Animator animator) {
                ivSwitch.setEnabled(true);
            }

            @Override
            public void onAnimationCancel(Animator animator) {
                ivSwitch.setEnabled(true);
            }

            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });
    }

}
